package com.hippo.drools.utils;

import lombok.extern.slf4j.Slf4j;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.spring.KModuleBeanFactoryPostProcessor;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

import static com.hippo.drools.config.RuleEngineConfig.BASE_RULES_PATH;
import static com.hippo.drools.config.RuleEngineConfig.RULES_PATH;

/**
 * @ClassName KieUtils
 * @Description TODO 热加载，需要重载规则文件，规则引擎容器要支持变动
 * @Author tangxl
 * @create 2023-05-08 10:23
 **/
@Slf4j
public class KieUtils {
    /**
     * 规则引擎容器
     */
    private static KieContainer kieContainer;

    /**
     * 规则引擎会话
     */
    private static KieSession kieSession;

    /**
     * 规则引擎容器后置处理器
     */
    private static KModuleBeanFactoryPostProcessor kModuleBeanFactoryPostProcessor;

    /**
     * 读取规则文件，并将规则文件写入到规则引擎系统内
     * @return
     * @throws IOException
     * @return
     */
    public static KieContainer getKieContainer() {
        return kieContainer;
    }

    /**
     * 设置规则引擎容器
     * @param kieContainer
     */
    public static void setKieContainer(KieContainer kieContainer) {
        KieUtils.kieContainer = kieContainer;
        kieSession = kieContainer.newKieSession();
    }

    /**
     * 获取规则引擎会话
     * @return
     */
    public static KieSession getKieSession() {
        return kieSession;
    }

    /**
     * 设置规则引擎会话
     * @param kieSession
     */
    public static void setKieSession(KieSession kieSession) {
        KieUtils.kieSession = kieSession;
    }

    /**
     * 获取规则文件
     * @return
     */
    public static KieServices getKieServices() {
        return KieServices.Factory.get();
    }

    /**
     * 获取初始化规则文件所在路径
     * @return
     */
    public static KModuleBeanFactoryPostProcessor getkModuleBeanFactoryPostProcessor() {
        return kModuleBeanFactoryPostProcessor;
    }

    /**
     * 设置规则引擎容器后置处理器
     * @param kModuleBeanFactoryPostProcessor
     */
    public static void setkModuleBeanFactoryPostProcessor(KModuleBeanFactoryPostProcessor kModuleBeanFactoryPostProcessor) {
        KieUtils.kModuleBeanFactoryPostProcessor = kModuleBeanFactoryPostProcessor;
    }

    public static void main(String[] args) throws IOException {
        // 获取初始化规则文件所在路径
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] files = resourcePatternResolver.getResources(BASE_RULES_PATH + RULES_PATH + "**/*");
        System.out.println(files.length);
    }
}
